/*
 * Copyright (c) 2013.
 * 游戏服务器核心代码编写人陈磊拥有使用权
 * 联系方式：E-mail:13638363871@163.com ;qq:502959937
 * 个人博客主页：http://my.oschina.net/chenleijava
 */

package com.dc.gameserver.serverCore.service.timerTask;/*
 * Copyright (c) 2013.
 * 游戏服务器核心代码编写人陈磊拥有使用权
 * 联系方式：E-mail:13638363871@163.com ;qq:502959937
 * 个人博客主页：http://my.oschina.net/chenleijava
 */


import com.dc.gameserver.baseConfig.Config;
import com.dc.gameserver.exceptions.dataException;
import com.dc.gameserver.serverCore.model.dbsql.mapper.TPointPrograssMapper;
import com.dc.gameserver.serverCore.model.dbsql.mapper.TRoleItemPropsMapper;
import com.dc.gameserver.serverCore.model.dbsql.mapper.TRoleMapper;
import com.dc.gameserver.serverCore.model.dbsql.modelCache.ModelCacheService;
import com.dc.gameserver.serverCore.model.dbsql.modelVo.*;
import com.dc.gameserver.serverCore.service.cardModule.CardBox;
import com.dc.gameserver.serverCore.service.cardModule.CardBoxManager;
import com.dc.gameserver.serverCore.service.character.PlayerInstance;
import com.dc.gameserver.serverCore.service.managerService.PlayerManagerService;
import javolution.util.FastTable;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author 石头哥哥
 *         Date: 13-11-19</br>
 *         Time: 下午3:43</br>
 *         Package: Server.ServerCore.Service.timer.quratzTimer</br>
 *         注解：资源回收 数据库字段重置，任务奖励 etc... ...
 */
@Service
@SuppressWarnings("unchecked")
public class clearAndResetTimerTask  implements executorTimerTask {

    @Resource
    private ModelCacheService modelCacheService;

    @Resource
    private TRoleMapper tRoleMapper;

    @Resource
    private TPointPrograssMapper pointPrograssMapper;

    @Resource
    private TRoleItemPropsMapper roleItemPropsMapper;

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;


    /**
     * 执行定时任务
     * 在指定的时间执行任务，任务结束，
     * 等待下一次时间点激活在执行 任务；
     */
    @Override
    public void executeTimerTask() throws SchedulerException, InterruptedException {
        //清理cardBox对象
        clearCardBox(CardBoxManager.cardBoxes);
        //每日清除玩家当天关卡完成次数   set value 0;
        clearLevelAndItemProps();
    }

    /**
     * 每日清除玩家当天关卡完成次数   set value 0;
     */
    private void clearLevelAndItemProps(){
        /**
         * 1.更新缓存（online player）；2.更新数据库
         */
        for (Map.Entry<Integer, PlayerInstance>entry: PlayerManagerService.INTEGER_PLAYER_INSTANCE_MAP.entrySet()){
            int roleID= entry.getValue().getID();
            List<TPointPrograss> levelList=
                    (List<TPointPrograss>) modelCacheService.
                            findListByPrefixID(ModelCacheService.POINT_PROGRASS_PREFIX(roleID));
            for (TPointPrograss prograss:levelList){
                prograss.setPointpercompletenum(0);
                pointPrograssMapper.updateByPrimaryKeySelective(prograss);
            }
        }

        for (Map.Entry<Integer, PlayerInstance>entry: PlayerManagerService.INTEGER_PLAYER_INSTANCE_MAP.entrySet()){
            int roleID= entry.getValue().getID();
            List<TRoleItemProps> tRoleItemPropsList=
                    (List<TRoleItemProps>) modelCacheService.
                            findListByPrefixID(ModelCacheService.PROPS_PREFIX(roleID));
            for (TRoleItemProps roleItemProps:tRoleItemPropsList){
                roleItemProps.setDayuselimit((byte)0);
                roleItemPropsMapper.updateByPrimaryKeySelective(roleItemProps);
            }
        }



        SqlSession sqlSession=sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);
        try {
            List<TRole> roleList=tRoleMapper.selectByExample(new TRoleExample());
            TPointPrograssMapper tPointPrograssMapper=sqlSession.getMapper(TPointPrograssMapper.class);
            /**关卡信息*/
            for (TRole role:roleList){
                TPointPrograss prograss=new TPointPrograss();
                prograss.setPointpercompletenum(0);  //set value o

                TPointPrograssExample pointPrograssExample=new TPointPrograssExample();
                TPointPrograssExample.Criteria criteria=pointPrograssExample.createCriteria();
                criteria.andRoleidEqualTo(role.getRoleid()); //角色编号

                tPointPrograssMapper.updateByPrimaryKey(prograss);

            }
            sqlSession.commit();  //手动提交
            sqlSession.clearCache();//清理缓存

            TRoleItemPropsMapper tRoleItemPropsMapper=sqlSession.getMapper(TRoleItemPropsMapper.class);
             /** 道具限制每天使用限制重置**/
            for (TRole role:roleList){
                TRoleItemProps itemProp=new TRoleItemProps();
                itemProp.setDayuselimit((byte)0);

                TRoleItemPropsExample roleItemPropsExample=new TRoleItemPropsExample();
                TRoleItemPropsExample.Criteria criteria=roleItemPropsExample.createCriteria();
                criteria.andOwneridEqualTo(role.getRoleid());

                tRoleItemPropsMapper.updateByExampleSelective(itemProp,roleItemPropsExample);
            }
            sqlSession.commit();  //手动提交
            sqlSession.clearCache();//清理缓存
            roleList.clear();
            roleList=null;
        } catch (dataException e){
            sqlSession.rollback();
        } finally {
            sqlSession.close();
            sqlSession=null;
        }
    }

    /**
     * 清理cardBox对象
     * @param cardBoxFastTable   cardBoxes容器对象
     */
    private void  clearCardBox(FastTable<CardBox> cardBoxFastTable){
        int size=cardBoxFastTable.size();
        if (size> Config.DEFAULT_VALUE.GAME_VALUE.cardBoxNum){
            for (CardBox cardBox:cardBoxFastTable){
                    cardBox.destroyCardBox();
                    CardBoxManager.cardBoxAtomicInteger.decrementAndGet();
                    CardBoxManager.cardBoxes.remove(cardBox);
                    cardBox=null;
                    if (cardBoxFastTable.size()== Config.DEFAULT_VALUE.GAME_VALUE.cardBoxNum){
                        return;
                    }
            }
        }
    }
}
